$(function(){

	var paramDatas = window.location.href.split("=");
	var parentId = paramDatas[2];
	var dataID = paramDatas[1].replace("&parentId","");
	var appExplorer = null;
	var containerWidth = 226 ;
	var $treeSortPanel = $('#tempo-tree-sort');
	var themeTreeSort='DEFAULT';
	var $searchBar = $(".tempo-app-rsmanage-search-bar");

	var indexOpts = $(".tempo-app-index-view");
	var contentOpts = $(".tempo-app-content-view");
	var $rightTaskView = $(".tempo-app-task-view");
	var indexOpts_addApp = $("#tempo-app-index-view-opts-addApp");
	var indexOpts_addFolder = $("#tempo-app-index-view-opts-addFolder");
	var datas = [];
	// 调整目录
	var $selectBtn = $('.select_target-btn');

	$('body').layout({
		west: {
			size: containerWidth,
			resizable : false,
			spacing_open : 0,
			closable : false
		},
		center: {

		}
	});
	$searchBar.searchbar({
		width: 196,
		isEnter: true,
		placeholder: TempoUtils.locale("aiview.rsmanageSearch"),
		onSearch: function(text){
			initExplorer(text);
		}
	});



	var bindIndexEvents = function(){
		//添加成果
		indexOpts_addApp.on("click",function(){
			if($(this).hasClass('ui-state-disabled')) {
				return ;
			}
			var data = appExplorer.gtree("getSelected");
			$m.loadHtml(contextPath + "/api/ai/app/view/add-achievement", $('body'), 'tempo-app-add-achievement-dialog',{
				callback: addApp,
				parentId: data.id
			});
		});
		//添加文件夹
		indexOpts_addFolder.on("click",function(){
			if($(this).hasClass('ui-state-disabled')) {
				return ;
			}
			var data = appExplorer.gtree("getSelected");
			meunEvent.createFolder(data);
		});
		//创建任务
		var $createTaskBtn = $('.create-task-btn');
		$createTaskBtn.button({
			emphasize: true,
			click: function(e){
				var data = appExplorer.gtree("getSelected");
				createTask(data);
			}
		});
		//删除任务
		var $deleteTaskBtn = $('.delete-task-btn');
		$deleteTaskBtn.button({
			emphasize: true,
			click: function(e){
				var data = appExplorer.gtree("getSelected");
				// deleteTask(data);
			}
		});
		// 更新树上服务的名称
		Eventbus.one('updateName.service', function(row) {
			if(row && row.id && row.name) {
				appExplorer.gtree("updateItemName", row.id, row.name);
				$('#ca-name').text(row.name);
			}
		});
		Eventbus.bind("updateserviceStatus.service",function(status,id) {
			$('div[objid="'+id+'"] #ca-status').text(status);
		});

		$selectBtn.button({
			emphasize: true,
			click:function(e){
				var data = appExplorer.gtree("getSelected");
				var folderid = $("#share_directory").attr("folderid");
				var pid = $("#share_directory").attr("pid");
				var ca = {
					"folderid":folderid,
					"pid":pid
				}
				meunEvent.move(data,ca,'调整目录成功');
			}
		});
		$("#share_directory").on("click",function(){
			var data = appExplorer.gtree("getSelected");
			var folderid = $(this).attr("folderid");
			var pid = $(this).attr("pid");
			var ca = {
				"folderid":folderid,
				"pid":pid
			}
			meunEvent.move(data,ca,TempoUtils.locale("aiview.rsmanageMoveOK"));
		})

	}

	var getSharePath = function(appid){
		$.ajax({
			url: contextPath + '/api/ai/app/category/path/get?t='+TempoUtils.uuid(),
			method: 'GET',
			data: {
				id: appid
			},
			success: function(rs) {
				if(rs.success){
					if(rs.success){
						if(rs.data){
							$("#share_directory").text(rs.data.path).attr({
								"title":rs.data.path,
								"pid":rs.data.id,
								"folderid":rs.data.parentId
							})
						}
					}
				}
			}
		});
	}

	/**
	 * 初始化表排序
	 */
	var initTreeSortButton = function(){
		$treeSortPanel.unbind('click').bind('click',function(e){
			configMenuOperator.showMenus(e);
		});
	}

	/**
	 * 菜单的操作
	 */
	var configMenuOperator = {
		/**
		 * 显示菜单
		 */
		showMenus:function(event){
			var modelMenu = utils.initMenu(event,configMenuOperator.exeucteMenuFor);
			modelMenu.contextmenu('selectItem',themeTreeSort);

		},
	}
	var utils = {
		initMenu:function(event,selectCallBack,data,dealMenuStatusCallBack){
			var modelMenu = $("<ul/>").appendTo($("body"));
			modelMenu.css({
				"z-index":1000
			});
			var menuData = utils.getMenusData();
			modelMenu.contextmenu({
				data:menuData,
				show:true,
				selectable:true,
				select:function(e,ui){
					var d = ui.linkEl.data;
					var menuId = ui.select.id;
					var data={
						id : "-1",
						sort:menuId,
					};
					themeTreeSort=menuId;
					var  words = $searchBar.searchbar("getValue").trim()||""
					switch(menuId){
						// 文件夹
						case "DEFAULT" : initExplorer(words);  break;
						case "ASC" : initExplorer(words); break;
						case "DESC" : initExplorer(words); break;
					}
				} ,
				close:function(){
					modelMenu.remove();
				}
			});
			if(dealMenuStatusCallBack){
				dealMenuStatusCallBack.call(modelMenu,data);
			}
			var posiLeft = event.pageX-16;
			var posiTop = event.pageY+16;
			var screenHeight = window.innerHeight;
			var minus = screenHeight - event.pageY;
			var menuHeight = modelMenu.height();
			if(minus < menuHeight){
				posiTop = posiTop - menuHeight;
			}

			modelMenu.contextmenu("show",{
				position:{
					left:posiLeft,
					top:posiTop
				},
				linkEl:this
			});
			return modelMenu;
		},
		/**
		 * 获取菜单数据
		 */
		getMenusData:function(){
			var menuData = [{
				text:'默认排序',
				id:'DEFAULT'
			},{
				text:'名称顺序',
				id:'ASC'
			},{
				text:'名称倒序',
				id:'DESC'
			}]
			return menuData;
		},
	}


	//加载左侧树
	var initExplorer = function(text) {
		$.ajax({
			url: contextPath + '/api/ai/app/category/warehouse/list',
			type: "post",
			data:{sort:"DEFAULT",id:parentId},
			success: function (rs) {
				var data = rs.data;
				for(var i = 0 ; i < data.length;i++){
					if(data[i].id == dataID){
						openApp(data[i]);
					}
				}
			}
		});
	};
	//成果管理左侧菜单事件rename createFolder OK了  delete ok  下架ok 退回ok  移动ok  上架  ok
	//对于文件夹本身的子文件数目的4个开放字段，后台是正确的，前台不是
	var meunEvent = {
		//需要开发文件夹面板选择上架
		add: function(data){
			$m.loadHtml(contextPath + "/api/ai/app/view/add-achievement", $('body'), 'tempo-app-add-achievement-dialog',{
				callback: addApp,
				parentId: data.id
			});
		},
		pull : function(data){
			$.post(contextPath+"/api/ai/app/service/pull", { "id": data.id },
				function(rs){
					if(rs.success){
						appExplorer.gtree("removeItem", data.id );
						if(appExplorer.gtree("getItem",rs.data.dataFold.id).length == 0){
							appExplorer.gtree("addItem",rs.data.dataFold,"unsort");
						}
						rs.data.dataLeaf.userName = data.userName;
						appExplorer.gtree("addItem",rs.data.dataLeaf,rs.data.dataFold.id);
						TempoUtils.showTip(TempoUtils.locale("aiview.rsmanagePullOk"));
					}else{
						if (rs.message) {
							TempoUtils.showTip(rs.message);
						} else {
							TempoUtils.showTip(TempoUtils.locale("aiview.rsmanagePullError"));
						}

					}
				});
		},
		rename : function(data){
			MenuEventInit.initDialog(TempoUtils.locale("aiview.rsmanageRename"),null,data.name,{T:TempoUtils.locale("aiview.rsmanageRenameOK"),F:TempoUtils.locale("aiview.rsmanageRenameError")},"/api/ai/app/category/rename",{id:data.id},function(pa){
				appExplorer.gtree('updateItemName',data.id,pa.name);
				//更新路径名称
				if($("#share_directory").length>0){
					var appItem = appExplorer.gtree("getSelected");
					getSharePath(appItem.id);
				}
			})
		},
		createFolder:function(data){
			var parentId = data.id;
			if(data.id == "-1"){
				parentId = "-1";
			}

			MenuEventInit.initDialog(
				TempoUtils.locale("aiview.rsmanageCreateFolder"),
				TempoUtils.locale("aiview.rsmanageInputFolder"),
				null,
				{
					T:TempoUtils.locale("aiview.rsmanageCreateFolderOK"),
					F:TempoUtils.locale("aiview.rsmanageCreateFolderError")
				},
				"/api/ai/app/category/create",
				{ parentId:parentId},
				function(pa,result) {
					appExplorer.gtree("addItem",result,parentId);
				},
				function(textareaObj) {
					$.ajax({
						url: contextPath + '/api/ai/app/folder/list-name',
						method: 'post',
						data:{
							parentId : parentId,
							prefix : "文件夹"
						},
						success: function(result) {
							textareaObj.val(result.data);
						}
					});

				})
		},

		deleteFolder:function(data) {
			$('<div/>').confirm({
				msg: TempoUtils.locale("aiview.deletetip"),
				ok: function() {
					var progressbar = $("<div/>").tempoprogressbar();
					$.post(contextPath+"/api/ai/app/category/delete", { "id": data.id }, function(rs){
						progressbar.tempoprogressbar("destroy");
						if(rs.success){
							appExplorer.gtree("removeItem", data.id );
							TempoUtils.showTip(TempoUtils.locale("aiview.rsmanageDeleteOK"));
							appExplorer.gtree("selectItem", data.parentId);
						}else{
							TempoUtils.showTip(rs.message);
						}
					});
				}
			});
		},
		move:function(data,ca,showTip){
			MenuEventInit.initTree(data,function(callBack,dialog){
				$.ajax({
					url: contextPath + '/api/ai/app/category/move',
					method: 'POST',
					data: {
						id: callBack.id,
						parentId:callBack.pid
					},
					success: function(rs) {
						dialog.dialog("destroy").remove();
						if(rs.success){
							var pid = callBack.pid;
							appExplorer.gtree("removeItem", data.id );
							data.parentId = callBack.pid;
							appExplorer.gtree("loadAndSelectItem",data,pid);
							TempoUtils.showTip(showTip||TempoUtils.locale("aiview.rsmanageMoveOK"));
						}else{
							TempoUtils.showTip(TempoUtils.locale("aiview.rsmanageMoveError"));
						}
					}
				})
			},ca);

		},
		"delete": function(data){
			$('<div/>').confirm({
				msg: TempoUtils.locale("aiview.rsmanageRemoveMsg"),
				ok: function() {
					var progressbar = $("<div/>").tempoprogressbar();
					$.post(contextPath+"/api/ai/app/category/delete", { "id": data.id, type: 'warehouse'}, function(rs){
						progressbar.tempoprogressbar("destroy");
						if(rs.success){
							appExplorer.gtree("removeItem", data.id );
							TempoUtils.showTip(TempoUtils.locale("aiview.rsmanageRemoveOK"));
							appExplorer.gtree("selectItem", data.parentId);
						}else{
							TempoUtils.showTip(data.message);
						}
					});
				}
			})
		},
		createTask: function(data) {createTask(data);},
		deleteTask: function(data) {deleteTask(data);}
	}

	//成果管理左侧点击事件
	var openApp = function(data) {
		//注释
		var rsManageId = data.id;//成果分类的ID/服务的ID
		var tag = true;
		if(data.parentId == "0"){
			tag = false;
		}
		indexOpts.hide();
		contentOpts.show();

		clickEvent.modifyInfo(data,tag);
		clickEvent.loadRigPage(rsManageId,tag);
	updateStatusLoop(data.id, null, data.ctype);
	}
	var information = {};
	var update = function(response) {
		var data = response.data || {};
		var resource = data.resource || {};
		var workspace = data.workspace || {};
		if (resource.name && resource.name.length > 20) {
			var trimThemeName = resource.name.substr(0, 20) + "...";
			$('.rs-right-top span[name="belong_theme"]').text(trimThemeName).attr('title', resource.name);
		} else {
			$('.rs-right-top span[name="belong_theme"]').text(resource.name).attr('title', resource.name);
		}
		if(workspace.name && workspace.name.trim()) {
			$('.rs-right-top span[name="belong_workspace"]').text(workspace.name).attr('title', workspace.name);
		} else {
			$('.rs-right-top span[name="belong_workspace"]').text(TempoUtils.locale("aiview.my_workspace"));
		}
	}
	//格式化日期 （显示为先月日）
	var formatCreateTime = function(createTime){
		var time=DateUtils.getCountTime(DateUtils.formatDate(createTime, 'yyyy-MM-dd hh:mm:ss')).split(" ");
		var createTime= DateUtils.formatDate(createTime, 'yyyy-MM-dd');
		// if(time[0]==0&&time[1]!=0){
		//  createTime=time[1]+"小时前";
		//  }
		// if(time[0]==0&&time[1]==0){
		//  createTime=time[2]+"分钟前";
		// }
		// if(time[0]==0&&time[1]==0&&time[2]==0){
		//    createTime=1+"分钟前";
		// }
		return createTime;
	}
	var clickEvent = {
		modifyInfo : function(data,tag){
			$('.rs-right-top span[id="ca-name"]').text(data.name);
			$('.rs-right-top span[id="ca-creator"]').text(data.userName);
			$('.ui-layout-pane-west').css("display","none");
			if(information[data.id]) {
				update(information[data.id]);
			} else {
				$.ajax({
					url: contextPath + '/api/ai/app/information',
					method: 'POST',
					data: {
						id: data.id
					},
					success: function(response) {
						update(response);
					}
				});
			}

			var status = "";
			var ctype = "";

			switch(data.ctype){
				case "sync":
					ctype = TempoUtils.locale("aiview.sync_service");
					if(data.parentId && data.parentId == "0"){
						status = TempoUtils.locale("aiview.status-publish");
					}else{
						status = MenuEventInit.getSyncStatus(data.id);
					}
					break;
				case "async":
					ctype = TempoUtils.locale("aiview.async_service");
					status = TempoUtils.locale("aiview.status-publish");
					break;
				case "stream":
					ctype = TempoUtils.locale("aiview.stream_service");
					if(data.parentId && data.parentId == "0"){
						status = TempoUtils.locale("aiview.status-publish");
					}else{
						status = MenuEventInit.getSyncStatus(data.id);
					}
					break;
			}
			$('#ca-type').text(ctype);
			if(ctype.length >3){
				$('#ca-type').text(ctype.substring(0,2));
			}
			var catime = "";//catime的处理
			if(data.parentId == "0"){
				catime += TempoUtils.locale("aiview.rsmanagePubTime")+": ";
				if(data.publishTime){
					catime += new Date(data.publishTime).Format("yyyy-MM-dd hh:mm:ss");
				}
			}else{
				catime += "发布于：";
				catime += formatCreateTime(data.putTime);
			}

			$('div[objid="'+data.id+'"] #ca-status').text(status);
			$('#ca-time').text(catime);
			$(".ui-layout-pane-center").css("left","0px");
			$(".ui-layout-pane-center").css("width","100%");
			$(".tempo-strap-header-right").empty();
			//$('#ca-status').parent().empty();
			$('.ui-dialog-title').text("服务详情");
			//var returnBack = $('.ui-dialog-titlebar-close').firstChild();
			// returnBack.removeClass("ui-button-icon ui-icon tempo-ui-icon tempo-ui-icon-delete");
			// returnBack.addClass("");
			getSharePath(data.id)
		},
		loadRigPage : function(rsManageId,tag){

			if(!tag){
				$('.rs-right-mid li.unsort').hide();
			}else{
				$('.rs-right-mid li.unsort').show();
			}
			$('.rs-right-mid').off('click').on('click',"li",function(e){
				var vurl = $(e.target).data("v");
				$(this).siblings().removeClass("rs-right-mid-select");
				$(this).addClass("rs-right-mid-select");
				if(vurl == null){
					return ;
				}
				$('.rs-right-bot').empty();
				//$('.rs-right-bot').height(window.innerHeight -  $('.rs-right-bot').offset().top);
				$m.loadPage(contextPath + "/api/ai/app/view/"+vurl+"?id="+rsManageId+"&&t="+TempoUtils.uuid(), $('.service-right-bot'));
			})
			$('.rs-right-mid li:eq(0)').trigger('click');
		}
	}
	//菜单点击事件中的辅助事件
	var MenuEventInit = {
		menus: [{
			text: TempoUtils.locale("aiview.menuAdd"),
			id:'add',
		},{
			text: TempoUtils.locale("aiview.rsmanageCreateFolder"),
			id:'createFolder',
		},{
			text: TempoUtils.locale("aidsview.create_new_task"),
			id:'createTask',
		},{
			text: TempoUtils.locale("aiview.menuMove"),
			id:'move',
		},{
			text: TempoUtils.locale("aiview.menuRename"),
			id:'rename',
		},{
			text: TempoUtils.locale("aiview.menuDel"),
			id:'deleteFolder',
		},{
			text: TempoUtils.locale("aiview.menuRemove"),
			id:'delete',
		},{
			text: TempoUtils.locale("aiview.menuRemove"),
			id: 'deleteTask',
		}],
		beforeMenuShow: function(data,ele) {
			var index = appExplorer.gtree('getNodeLevel',data.id)
			if(data && ( data.ctype == 'folder' || data.id == "-1" ) ) {
				if(data.id == "-1" ){
					return ['createFolder'];
				}
				if(index >= 2) {
					return ['add', 'rename', 'deleteFolder'];
				}
				return ['add', 'rename','createFolder', 'deleteFolder'];
			} else if (data && data.ctype == 'task') {
				return [];
			} else {
				return ['move', 'delete'];
			}
			return [];
		},
		getSyncStatus:function(id){
			var status = TempoUtils.locale("aiview.serviceUnStart");
			/*var process = $("<div/>").tempoprogressbar();
            $.ajax({
                url:contextPath + '/api/ai/app/model/status/' + id,
                method: 'POST',
                async:false,
                success: function(rs) {
                    if(rs.success){
                        if( rs.data == 'STARTING'){
                            status = TempoUtils.locale("aiview.status-starting");
                        }else if( rs.data == 'RUNNING'){
                            status = TempoUtils.locale("aiview.serviceHasStart");
                        }else{
                            status = TempoUtils.locale("aiview.serviceUnStart");

                        }
                    }
                },
                complete:function(){
                    process.tempoprogressbar("destroy");
                }
            });*/
			updateStatusLoop(id);
			return status;
		},
		initTree : function(data,callback,ca){
			var moveTitle = TempoUtils.locale("aiview.menuMove");
			if(ca!=null){
				//调整目录
				moveTitle = TempoUtils.locale("aiview.app_select_target");
			}
			var folderid = "";
			var dialog = $("<div/>", {
				'class' : 'tempo-app-achievement-move-dialog'
			});
			var content = $("<div>").addClass("tempo-strap-dialog-tree-container").appendTo(dialog);
			content.css('height', '100%');
			var $treeDiv = $("<div>").addClass("tempo-strap-dialog-tree").appendTo(content);
			$treeDiv.css('width', ' calc(100% - 35px)');
			dialog.dialog({
				modal : true,
				width : 500,
				height : 400,
				resizable : false,
				title : moveTitle,
				open:function(){
					$.ajax({
						url: contextPath + '/api/ai/app/category/tree',
						method: 'POST',
						data: {
							id : "-1"
						},
						success: function(rs) {

							if(rs.success){
								var rootfolder = rs.data[0];
								var datas = rootfolder.children
								if (datas.length > 0) {
									$treeDiv.gtree({
										data: rs.data,
										getItemIcon:function(nodeData){
											return 'tempo-ui-icon-api-folder-close';
										},
										enableSelect: true,
										renderComplete:function(){
											$treeDiv.gtree('expand','-1');
											if(ca!=null){
												if(ca.folderid=="-1"){
													$treeDiv.gtree("clickItem", ca.pid)
												}else{
													$treeDiv.gtree("clickItem", ca.folderid);
													$treeDiv.gtree("clickItem", ca.pid)
												}
											}
										}
									});
								} else {
									// 如果没有可选文件夹，添加提示
									$("<div>").css({
										'position': 'absolute',
										'height': '100%',
										'width': 'calc(100% - 40px)',
										'line-height': '298px',
										'top': '0px',
										'text-align': 'center',
										'font-size': '14px'
									}).text('请先在模型仓库中中创建分类文件夹').appendTo(content);
								}
							}else{
								TempoUtils.showTip(TempoUtils.locale("aiview.rsLoadErr"));
							}
						}
					});
				},
				buttons : [ {
					text : TempoUtils.locale("aiview.confirm"),
					id: "theme_operate_button",
					click : function() {
						try {
							var node = $treeDiv.gtree("getSelected");
							if(node && node.id != '-1') {
								if(callback != null && typeof callback == "function"){
									callback({pid:node.id,id:data.id},dialog);
								}
							}else{
								TempoUtils.showTip(TempoUtils.locale("aiview.rsSelFol"));
							}
						} catch (e) {
							dialog.dialog("destroy").remove();
						}
					}
				},{
					text : TempoUtils.locale("aiview.cancel"),
					id: "theme_operate_button",
					click : function() {
						dialog.dialog("destroy").remove();
					}
				}  ],
				close : function() {
					// 销毁弹出框,并返回
					dialog.dialog("destroy").remove();
				}
			});
		},
		initDialog: function(title,placeholder,initName,showTips,addr,params,callBack, callBack2){
			var paramDialog = $('<div class="tempo-rs-operate" style="text-align:center;width:100%;height:100%;"/></div>').appendTo($('body'));
			var renameDiv = $('<div id="rename-category">').appendTo(paramDialog);
			if(placeholder == null){
				placeholder = "";
			}
			if(addr.indexOf("decline") > -1){
				$("<label class='theme_operate_input_name'>"+TempoUtils.locale("aiview.descript")+"</label>").appendTo(renameDiv);
			}else{
				$("<label class='theme_operate_input_name'>"+TempoUtils.locale("aiview.name")+"</label>").appendTo(renameDiv);
			}
			var textArea = $('<input id="rename-category-textarea"></input>').addClass("tempo-validatebox").appendTo(renameDiv);
			paramDialog.dialog({
				title : title,
				autoOpen : true,
				width : 500,
				height : 197,
				resizable : false,
				modal : true,
				close : function() {
					paramDialog.find("#rename-category").empty();
					paramDialog.dialog('destroy');
					paramDialog.remove();
				},
				open : function() {
					textArea.validatebox({
						//模型仓库新建文件夹命名校验可以使用特殊字符命名
						//valids:[/^[^~!@#\$%\^&\*\+\[\]\|\}\{\\;':",\.\/<>\?`]+$/],
						tip:TempoUtils.locale("resource.name_valid_tip"),
						required: true,
						maxLength: 60,
						autofill: false
					});
					if(initName != null){
						textArea.val(initName);
					}
					if (callBack2) {
						callBack2(textArea);
					}
				},
				buttons : [
					{
						text : TempoUtils.locale("aiview.confirm"),
						id: "theme_operate_button",
						click : function() {

							if(!paramDialog.find("#rename-category-textarea").validatebox("doValidate")){
								return false;
							}
							var reqParams = {name:paramDialog.find("#rename-category-textarea").val()};
							if(addr.indexOf("decline") > -1){//backcomment退回说明字段
								reqParams = {backComment:paramDialog.find("#rename-category-textarea").val()};
							}
							$.post(contextPath+addr, $.extend(params,reqParams),
								function(rs){
									if(rs.success){
										paramDialog.dialog('destroy');
										paramDialog.remove();
										callBack({name:paramDialog.find("#rename-category-textarea").val()},rs.data);
										//TempoUtils.showTip(showTips["T"]);
									}else{
										if(rs.message!=null &&　rs.message!=""){
											TempoUtils.showTip(rs.message);
										}else{
											TempoUtils.showTip(showTips["F"]);
										}
									}

								});

						}
					},
					{
						text : TempoUtils.locale("aiview.cancel"),
						id: "theme_operate_button",
						click : function() {
							paramDialog.dialog('destroy');
							paramDialog.remove();
						}
					}
				]
			});


		}
	}

	var deleteEmptyTheme = function(themeid){
		//主题下为空，则删除主题
		var parentData = {id:themeid}
		var childrenLength = appExplorer.gtree("getChildren",parentData).length;
		if (childrenLength == 0){
			appExplorer.gtree("removeItem",themeid);
		}
	}

	/**
	 * 添加成果
	 */
	var addApp = function(parentId, apps, result) {
		if(result.success) {
			// 添加到左侧树上
			for(var d in result.data) {
				appExplorer.gtree("addItem",result.data[d], parentId);
			}
			TempoUtils.showTip(TempoUtils.locale("aiview.addSuccess"));
		} else {
			TempoUtils.showTip(TempoUtils.locale("aiview.addFailed"));
		}
	}
	/**
	 * 创建任务
	 */
	var createTask = function(data) {
		$m.loadHtml(contextPath + "/api/ai/view/load/app-single-task-dialog", $('body'), 'tempo-app-add-task-dialog', {
			callback: function(task, job) {
				var leaf = {};
				var leaf = {};
				var trigger = job.trigger;
				leaf.id = job.id;
				leaf.name = trigger.name;
				leaf.type = 'task';
				leaf.fileType = 'FILE';
				leaf.parentId = data.id;
				leaf.fileType = 'FILE';
				leaf.ctype = 'task';
				appExplorer.gtree("addItem", leaf, data.id);
			},
			data: data
		});
	}
	var deleteTask = function(data) {
		var id= data.id;
		$('<div/>').confirm({
			msg: '是否移除该任务？',
			ok: function() {
				var progressbar = $("<div/>").tempoprogressbar();
				$.post(contextPath+"/api/ai/app/schedule/info", { "id": id}, function(info){
					if(info.data){
						var jobinfo = info.data ;
						var triggerid=jobinfo.jobId;
						$.post(contextPath+"/api/ai/app/schedule/job/delete", { "id": id,"triggerId":triggerid}, function(rs){
							progressbar.tempoprogressbar("destroy");
							if(rs.success){
								appExplorer.gtree("removeItem", id);
								TempoUtils.showTip(TempoUtils.locale("aiview.rsmanageDeleteOK"));
								appExplorer.gtree("selectItem", data.parentId);
							}else{
								TempoUtils.showTip(rs.message);
							}
						});
					}else{
						progressbar.tempoprogressbar("destroy");
						TempoUtils.showTip(info.message);
					}
				});
			}
		})
	}

	var validateForm = function(dialog, isEdit) {
		var v = dialog.find('form').formValidate();
		var jobconfig = TempoUtils.getRecord(dialog.find('form'));
		var triggerName = jobconfig.name;
		var isRaname = false;
		$.ajax({
			url : contextPath + '/api/ai/mine/publish/listAllTriggerName',
			type : 'post',
			async:false,
			success : function(triggerNames) {
				if (triggerNames) {
					isRaname = triggerNames.indexOf(triggerName) > -1;
				}
			}
		});
		if (isRaname) {
			$("<div/>").alert({msg : TempoUtils.locale("mine.triggernameerror"), height : 180});
			return false;
		}
		return v && (function(){
			console.log(jobconfig);
			if(jobconfig.starttime && jobconfig.endtime) {
				var s = new Date(jobconfig.starttime);
				var e = new Date(jobconfig.endtime);
				if(s.getTime() > e.getTime()) {
					$("<div/>").alert({msg : TempoUtils.locale("mine.shengxiaoshijianerror"), height : 180});
					return false;
				}
			}
			if(jobconfig.stime && jobconfig.etime) {
				if(jobconfig.stime >= jobconfig.etime && jobconfig.runType == 'inner-day') {
					$("<div/>").alert({msg : TempoUtils.locale("mine.kaishishijianerror"), height : 180});
					return false;
				}
				if(jobconfig.stime == jobconfig.etime && jobconfig.runType == 'outer-day') {
					$("<div/>").alert({msg : TempoUtils.locale("mine.schedule-stime-not-equls-etime"), height : 180});
					return false;
				}
			}
			return true;
		})();
	}

	var saveTaskConfig = function(dialog, flowInfo) {
		if(!validateForm(dialog, flowInfo)){
			return;
		}
		var job = {
			trigger : {
			},
			publishFlowIds : []
		};
		var triggerParam = {};
		var trigger = job.trigger;
		var publishFlowIds = [];
		var publishFlowNames = [];
		//调度信息
		var jobconfig = dialog.find('#tempo-mine-flow-config').serializeArray();

		// 添加对复选框值的处理，转变为一个属性值
		$.each(jobconfig, function(index, item){
			if(!item.name.startsWith('flow_')){
				if(trigger[item.name]) {
					if(Array.isArray(trigger[item.name])) {
						trigger[item.name].push(item.value);
					} else {
						trigger[item.name] = [trigger[item.name], item.value];
					}
				} else {
					trigger[item.name] = item.value;
				}
			}
		});
		// 解决IE10下面选中保存不了问题
		var isChecked = dialog.find('input[name=retry]').is(':checked');
		if(!trigger.retry && isChecked) {
			trigger.retry = 'on';
		}

		if((dialog.find('input[name=dayofweek]').length && !trigger['dayofweek'])
			|| (dialog.find('input[name=dayofmonth]').length && !trigger['dayofmonth'])) {
			$("<div/>").alert({msg : TempoUtils.locale("mine.qingxuanzeyunxingshijian"), height : 180});
			return false;
		}
		// 处理数组类型值，转换为逗号分割的字符串
		Array.isArray(trigger['dayofweek']) && (trigger['rundate'] = trigger['dayofweek'].join(','));
		Array.isArray(trigger['dayofmonth']) && (trigger['rundate'] = trigger['dayofmonth'].join(','));
		trigger['dayofweek']  && !trigger['rundate'] && (trigger['rundate'] = trigger['dayofweek']);
		trigger['dayofmonth'] && !trigger['rundate'] && (trigger['rundate'] = trigger['dayofmonth']);
		delete trigger['dayofweek'];
		delete trigger['dayofmonth'];
		console.log(JSON.stringify(trigger))
		trigger.interval = Number(trigger.interval);
		if(trigger.retryNum) trigger.retryNum = Number(trigger.retryNum);
		var relatedFlow = [];
		var rflowObj = {};
		rflowObj["flow_current"] = flowInfo.id;
		relatedFlow.push(rflowObj);
		triggerParam.flowsInJob = relatedFlow;
		job.publishFlowIds = flowInfo.id;
		job.publishFlowNames = flowInfo.name;;
		//流程配置参数
		triggerParam.flowsParam = {};
		triggerParam.flowsParam[flowInfo.id] = getCurrentFlowParams(dialog);
		job.trigger.param = JSON.stringify(triggerParam);

		var process = $("<div/>").tempoprogressbar();
		var url = contextPath + '/api/ai/app/schedule/job/save';
		$.ajax({
			url : url,
			type : 'post',
			data : JSON.stringify(job),
			contentType : 'application/json',
			success : function(obj) {
				process.tempoprogressbar("destroy");
				if (obj &&  obj.data && obj.data.status) {
					$('#mine-opt-job-grid').jqGrid().trigger("reloadGrid");
					dialog.dialog("destroy");
				} else {
					$("<div/>").alert({msg : obj.data.error, height : 180, width: 400});
				}
			},
			error:function(data){
				process.tempoprogressbar("destroy");
			}
		});

	}

	var getCurrentFlowParams = function(dialog){
		var paramsTable = dialog.find('#flowParamsContainer table');
		var currentFlowParams = []
		var paramsLine = paramsTable.find('tbody tr');
		paramsLine.each(function(i){
			var paramName = $(this).find('input.flow_paramname').val();
			var paramType = $(this).find('input.flow_paramtype').val();
			var paramId = $(this).find('input.flow_paramid').val();
			var paramValue = $(this).find('select.flow_paramvalue').selectmenu('getValue');
			var param = {};
			param.paramName = paramName;
			param.paramValue = paramValue;
			param.paramId = paramId;
			param.paramType = paramType;
			if(!$.isEmptyObject(param)){
				currentFlowParams.push(param);
			}
		});
		return currentFlowParams;
	}

	var setFlowParams = function(dialog, flowInfo) {

		var flowid = flowInfo.id;
		dialog.find('#flowParamsContainer').hide();
		var paramLabel = TempoUtils.locale("mine.publish-mine-job-param-label");
		dialog.find("#publish-mine-job-param-label").text(flowInfo.name+'-'+paramLabel);
		var grid = dialog.find('#setFlowParamTable').find('tbody').empty();
		$.ajax({
			url : contextPath+"/api/ai/app/schedule/flowparams/get/" + flowid,
			type : 'post',
			success : function(result){

				if(result && result.data && result.data.length > 0){
					initParamGrid(dialog, result.data);
				}
			}
		});
	}

	var getFlowParams = function(type, paramValueInput, value, nodeType) {
		var pss = [];
		if(type == 'datasource'){
			var process = $("<div/>").tempoprogressbar();
			$.ajax({
				url:contextPath + '/api/ai/node/io/list-datasources',
				type:'post',
				success:function(rs) {
					process.tempoprogressbar("destroy");
					var data = rs.data;
					var itemHtml = [];
					for(var i =0;i<data.length;i++){
						var dataItem = data[i];
						// 屏蔽模型数据源、presto数据源、impala数据源
						if (nodeType == 'readrdbms') {
							if (!dataItem.type || TempoMineUtils.inputSupportType.indexOf(dataItem.type) == -1) {
								continue;
							}
						}
						if (nodeType == 'writerdbms') {
							if (!dataItem.type || TempoMineUtils.inputSupportType.indexOf(dataItem.type) == -1 || (dataItem.purpose && dataItem.purpose != "1")) {
								continue;
							}
						}

						if (nodeType == 'readhive') {
							if (dataItem.type != 'hive') {
								continue;
							}
						}
						if(nodeType == 'writehive'){
							if('hive' != dataItem.type  || (dataItem.purpose && dataItem.purpose != "1")){
								continue;
							}
						}
						if (nodeType == "readinfluxdb") {
							if (!(dataItem.type == "influxdb" || dataItem.type == "influxdb2")) {
								continue;
							}
						}
						if( nodeType == "readiotdb"){
							if (dataItem.type != 'iotdb') {
								continue;
							}
						}
						if( nodeType == "writeiotdb"){
							//不是iotdb  或者不能写入
							if ('iotdb' != dataItem.type  || (dataItem.purpose && dataItem.purpose != "1")) {
								continue;
							}
						}
						itemHtml.push('<option value="' + dataItem.code + '">' + dataItem.name + '</option>')
					}
					var html = itemHtml.join('');
					paramValueInput.html(html);
					paramValueInput.selectmenu({
						editable : false,
						width : 150,
						labelForTitle: true
					}).selectmenu('setValue', value).selectmenu('refresh');
				}
			});
		} else {
			var items = TempoMineUtils.getConstFlowParams();
			if(items){
				for(name in items){
					pss.push('<option value="' + name + '">' + items[name] + '</option>')
				}
			}
			var html = pss.join('');
			paramValueInput.html(html);
			paramValueInput.selectmenu({
				editable : true,
				width : 150,
				labelForTitle: true
			}).selectmenu('setValue', value);
		}

	}

	var initParamGrid = function(dialog, ps){
		var grid = dialog.find('#setFlowParamTable');
		dialog.find('#flowParamsContainer').show();
		if (ps && ps.length > 0) {
			for (var i = 0; i < ps.length; i++) {
				var tr = $('<tr>').appendTo(grid);
				var p = ps[i];
				var paramName = p.paramName;
				var paramValue = p.paramValue;
				var paramType = p.paramType;
				var paramId = p.paramId;
				var nodeType = p.nodeType;
				var paramNameTd = $('<td>').appendTo(tr);
				var paramNameInput = $('<input name="paramName">')
					.addClass('flow_paramname')
					.appendTo(paramNameTd)
					.val(paramName);
				var paramTypeInput = $('<input name="paramType" type="hidden">').addClass('flow_paramtype').appendTo(paramNameTd).val(paramType);
				var paramTypeInput = $('<input name="paramId" type="hidden">').addClass('flow_paramid').appendTo(paramNameTd).val(paramId);
				var paramValueTd = $('<td>').appendTo(tr);
				var paramValueInput = $('<select name="paramValue">').addClass('flow_paramvalue').appendTo(paramValueTd);
				paramNameInput.validatebox({width : 100, readonly : true});

				paramNameInput.attr('title', paramName);
				getFlowParams(paramType, paramValueInput, paramValue,nodeType);
			}
		}
	};

	var initFormData = function(dialog) {
		TempoUtils.parserUi(dialog, {});
		dialog.find('input[name="retry"]').checkbox({
			change: function(e, ui) {
				console.log(e, ui);
				if(ui.checked) {
					dialog.find('input[name="retryNum"]').numberbox({disabled: false, required: true});
				} else {
					dialog.find('input[name="retryNum"]').numberbox({disabled: true, required: false});
				}
			}
		});

		dialog.find('.datefield').datepicker({
			dateFormat: 'yy-mm-dd',
			onClose : function(){
				if($(this).val()){
					$(this).validatebox('response', $(this).val());
				}
			},
			onSelect :function(){

			},
			onChangeMonthYear : function(year, month, inst){
				var month = inst.selectedMonth + 1;
				var day = inst.selectedDay;
				var format = function(v) { return String(v).length > 1 ? v : ('0' + v) }
				$(this).val(inst.selectedYear + '-' + format(month) + '-' + format(inst.selectedDay));
				$.datepicker._hideDatepicker(this);
			}
		});
		dialog.find('.timefield').timepicker({
			onClose : function(){
				if($(this).val()){
					$(this).validatebox('response', $(this).val());
				}
			},
			onSelect :function(){

			},
			timeInput : true
		});

		var internalInput = dialog.find('input[name=interval]');
		dialog.find('select[name="triggertype"]').selectmenu({
			selectFirst: false,
			change: function(e, ui) {
				console.log(e, ui);
				changeTriggerType(ui.item.value);
			}
		});

		var changeTriggerType = function(value) {
			if(value == "-2") {
				//分钟
				switchShowItem(dialog, false, true, false, true, 1);
				dialog.find('.internal-unit').text(TempoUtils.locale("mine.publish-mine-job-triggertype-minute"));
				internalInput.numberbox({max: 59, min: 1}).val(30);
			} else if(value == "-1") {
				//小时
				switchShowItem(dialog, false, true, false, true, 1);
				dialog.find('.internal-unit').text(TempoUtils.locale("mine.publish-mine-job-triggertype-hour"));
				internalInput.numberbox({max: 23, min: 1}).val(3);
			} else if(value == "0") {
				//天
				switchShowItem(dialog, false, false, true, true, 3);
				dialog.find('.internal-unit').text(TempoUtils.locale("mine.publish-mine-job-triggertype-day"));
				internalInput.numberbox({max: 31, min: 1}).val(1);
			} else if(value == "1") {
				//周
				dialog.find('.internal-unit').text(TempoUtils.locale("mine.publish-mine-job-triggertype-week"));
				switchShowItem(dialog, true, false, true, false);
				buildWeeks(dialog);
				internalInput.numberbox({max: 6, min: 1}).val(1);
			} else if(value == "2") {
				//月
				switchShowItem(dialog, true, false, true, true, 2);
				dialog.find('.internal-unit').text(TempoUtils.locale("mine.publish-mine-job-triggertype-month"));
				buildDays(dialog);
				internalInput.numberbox({max: 11, min: 1}).val(1);
			}
		}

		dialog.find('select[name="triggertype"]').val(0).selectmenu('refresh');
		changeTriggerType(0);
		dialog.find('input[name=starttime]').val(DateUtils.formatDate(new Date()));
	}

	/**
	 * 调度时间切换方法
	 */
	var switchShowItem = function(dialog, timesRow, timeRange, dayTime, interval, dayMonthYear) {
		var _onoff = $.fn.onoff;
		$.fn.onoff = function(value) {
			var element = $(this);
			if(value) {
				element.show();
			} else {
				element.hide();
			}
			element.find('input').each(function(index, ele) {
				var role = $(ele).attr('ui-role');
				if(role == 'validatebox' || role == 'numberbox') {
					!value ? $(ele)[role]('disable') : $(ele)[role]('enable');
				}
			});
		}
		dialog.find('.times-row').onoff(timesRow);
		dialog.find('.times-board').empty();
		if(timeRange) {
			dialog.find('.day-of-time-range-row input[name=stime]')
				.validatebox({required: true}).validatebox('validate');
		} else {
			dialog.find('.day-of-time-range-row input[name=stime]')
				.validatebox({required: false}).validatebox('validate');
		}
		dialog.find('.day-of-time-range-row').onoff(timeRange);
		dialog.find('.day-of-time-row').onoff(dayTime);
		dialog.find('.time-interval-row').onoff(interval);
		if(interval && dayMonthYear != undefined) {
			dialog.find('.time-of-day').onoff(dayMonthYear == 1);
			dialog.find('input.time-of-day').hide().radio('check', dayMonthYear == 1 ? 'outer-day' : '');
			dialog.find('.day-of-month').onoff(dayMonthYear == 2);
			dialog.find('input.day-of-month').hide().radio('check', dayMonthYear == 2 ? 'outer-month' : '');
			dialog.find('.month-of-year').onoff(dayMonthYear == 3);
			dialog.find('input.month-of-year').hide().radio('check', dayMonthYear == 3 ? 'outer-year' : '');
		}
		$.fn.onoff = _onoff;
	}

	/**
	 * 构建周页面
	 */
	var buildWeeks = function(dialog) {
		var board = dialog.find('.times-board');
		var weeks = [2, 3, 4, 5, 6, 7, 1];
		var weekName = [TempoUtils.locale("mine.xinqiyi"),
			TempoUtils.locale("mine.xinqier"),
			TempoUtils.locale("mine.xinqisan"),
			TempoUtils.locale("mine.xinqisi"),
			TempoUtils.locale("mine.xinqiwu"),
			TempoUtils.locale("mine.xinqiliu"),
			TempoUtils.locale("mine.xinqitian")
		];
		weeks.forEach(function(e, i) {
			var span = $("<span style='display: inline-block;padding-left: 15px;width: 105px;'></span>").appendTo(board);
			$("<input ui-role='checkbox' name='dayofweek' type='checkbox'/>").val(e).appendTo(span);
			$("<label/>").text(weekName[i]).appendTo(span);
		});
		TempoUtils.parserUi(board, {});
	};

	/**
	 * 构建天页面
	 */
	var buildDays = function(dialog) {
		var board = dialog.find('.times-board');
		for(var i = 1; i <= 31; i++) {
			var span = $("<span style='display: inline-block;padding-left: 15px;width: 105px;'></span>").appendTo(board);
			$("<input ui-role='checkbox' name='dayofmonth' type='checkbox'/>")
				.val(i)
				.addClass('day-of-month-' + i)
				.appendTo(span);
			$("<label/>").text(i + TempoUtils.locale("mine.hao")).appendTo(span);
		}
		var lastSpan = $("<span style='display: inline-block;padding-left: 15px;width: 105px;'></span>").appendTo(board);
		$("<input ui-role='checkbox' name='dayofmonth' type='checkbox'/>")
			.val("L")
			.addClass('day-of-month-L')
			.appendTo(lastSpan);
		$("<label/>").text(TempoUtils.locale("mine.zuihouyitian")).appendTo(lastSpan);
		TempoUtils.parserUi(board, {});
	}

	var modifyInfo = function(data){

		$('.rs-right-top span[id="task-creator"]').text(data.userName);
		var catime = new Date(data.createTime).Format("yyyy-MM-dd hh:mm:ss");
		$('.rs-right-top span[id="task-time"]').text(catime);
		$.ajax({
			url : contextPath + '/api/ai/mine/publish/listJobInfo',
			type : 'post',
			dataType:'json',
			data : {
				id : data.id
			},
			success : function(result) {
				if ("true" == result.flag) {
					var job = result.job;
					var taskStatusDesc = "生效";
					if(job.trigger.status == "PAUSED" || job.trigger.status == "PAUSED_BLOCKED"){
						taskStatusDesc = '暂停';
					} else if(job.trigger.status == "COMPLETE"){
						taskStatusDesc = '失效';
					} else if (job.trigger.status == "AWAIT") {
						taskStatusDesc = '等待';
					}

					//$('.rs-right-top span[id="task-createTime"]').text(formatCreateTime(job.createTime));
					$('.task-runtStatus').text(taskStatusDesc);
					$('.tempo-app-task-view span[id="ca-name"]').text(job.trigger.name);
				}
			}
		});
		if(information[data.id]) {
			update(information[data.id]);
		} else {
			$.ajax({
				url: contextPath + '/api/ai/app/information',
				method: 'POST',
				data: {
					id: data.parentId
				},
				success: function(response) {
					update(response);
				}
			});
		}
	}

	var loadTaskRightPage = function(data){

		$('.task-right-bot li.unsort').show();
		$('.task-right-mid').off('click').on('click',"li",function(e){

			var vurl = $(e.target).data("v");
			$(this).siblings().removeClass("rs-right-mid-select");
			$(this).addClass("rs-right-mid-select");
			if(vurl == null){
				return ;
			}
			$('.task-right-bot').empty();
			var id = data.id;
			if ("overview" == vurl) {
				id = data.parentId;
			}
			$m.loadPage(contextPath + "/api/ai/app/view/"+vurl+"?id="+id+"&&t="+TempoUtils.uuid()+"&&serviceId="+data.parentId, $('.task-right-bot'));
		})
		$('.task-right-mid li:eq(0)').trigger('click');
	}
	// 请求服务状态
	var isAlive = function(fn, uid) {
		var id = uid || row.id
		$.postForm({
			url: contextPath + '/api/ai/app/model/status/' + id,
			success:  function(rp) {
				fn(rp.data == 'STARTING' || rp.data == 'RUNNING', rp.data);
			}
		});
	}
	var updateStatusLoop = function(id, updateFn, type) {
		if(type != 'sync' && type != 'stream') {
			window.loopUpdateTimer = -1;
			return ;
		}
		var timer = setTimeout(function() {
			var fn = arguments.callee;
			isAlive(function(d, status) {
				if(window.loopUpdateTimer != timer) {
					return ;
				}
				if(status == 'STARTING') {
					serviceStatus = TempoUtils.locale("aiview.serviceStarting");
					Eventbus.trigger('updateserviceStatus.service', serviceStatus,id);
					timer = setTimeout(fn, 1000);
					window.loopUpdateTimer = timer
				} else if(status == 'RUNNING'){
					if(typeof row != "undefined") row.launchState = status;
					$('div[objid="'+id+'"] a.start-button').text(TempoUtils.locale("aiview.serviceStop"));
					$('div[objid="'+id+'"] #ca-status').text(TempoUtils.locale("aiview.serviceHasStart"));
					serviceStatus = TempoUtils.locale("aiview.serviceHasStart");
					Eventbus.trigger('updateserviceStatus.service', serviceStatus,id);
					$('div[objid="'+id+'"] a.start-button').removeClass("ui-state-disabled");
					if(updateFn) updateFn();
				} else {
					$('div[objid="'+id+'"] a.start-button').text(TempoUtils.locale("aiview.serviceStart"));
					$('div[objid="'+id+'"] #ca-status').text(TempoUtils.locale("aiview.serviceUnStart"));
					serviceStatus = TempoUtils.locale("aiview.serviceUnStart");
					Eventbus.trigger('updateserviceStatus.service', serviceStatus,id);
					$('div[objid="'+id+'"] a.start-button').removeClass("ui-state-disabled");
					if(updateFn) updateFn();
				}
			}, id);
		});
		window.loopUpdateTimer = timer;
	}
	Eventbus.bind('updateStatusLoop.service', updateStatusLoop);

	initExplorer();
	initTreeSortButton();
	bindIndexEvents();

});